package com.common.service.impl;

import com.common.config.FileStorageConfig;
import com.common.entity.FileStorageVO;
import com.common.exception.FileStorageException;
import com.common.exception.InvalidFilePathException;
import com.common.service.FileStorageService;
import com.common.util.FileUtils;
import com.common.util.UUIDUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Objects;

@Service
public class LocalFileStorageServiceImpl implements FileStorageService {

    private final Path storagePath;

    public LocalFileStorageServiceImpl(FileStorageConfig config) {
        this.storagePath = config.fileStoragePath();
        createStoragePath();
    }

    private void createStoragePath() {
        try {
            Files.createDirectories(storagePath);
        } catch (IOException e) {
            throw new FileStorageException("无法创建存储目录",e);
        }
    }

    @Override
    public FileStorageVO storeFile(MultipartFile file) {

        String filename = StringUtils.cleanPath(
                Objects.requireNonNull(file.getOriginalFilename())
        );

        if(filename.contains("..")){
            throw new InvalidFilePathException(filename);
        }

        String fileExtension = FileUtils.getFileExtension(filename);
        String newFileName = UUIDUtil.getUUID() + fileExtension;

        try {
            Path targetLocation = storagePath.resolve(newFileName);

            Files.copy(
                    file.getInputStream(),
                    targetLocation,
                    StandardCopyOption.REPLACE_EXISTING
            );
            return new FileStorageVO(newFileName,filename,fileExtension);
        } catch (IOException ex) {
            throw new FileStorageException("保存文件失败: " + filename, ex);
        }
    }
}
